<template>
    <div class="app-container">
        <div class="customContainer">
            <!-- 搜索头 -->
            <el-form :inline="true" :model="formInline" size="small">
<!--                <el-form-item>-->
<!--                    <el-select-->
<!--                            placeholder="选择门店"-->
<!--                            v-model="formInline.store_id"-->
<!--                            @change="listArray"-->
<!--                            style="width:250px"-->
<!--                            filterable>-->
<!--                        <el-option-->
<!--                                v-for="item in store_list"-->
<!--                                :key="item.id"-->
<!--                                :label="item.name"-->
<!--                                :value="item.id"-->
<!--                        ></el-option>-->
<!--                    </el-select>-->
<!--                </el-form-item>-->
                <el-form-item>
                    <el-date-picker style="width:240px" v-model="pickerDate" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels range-separator="-"
                                    :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"  @change="timeListArray()"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <span style="color: #888;">状态：</span>
                    <el-select
                            v-model="formInline.status"
                            style="width: 150px"
                            placeholder="请选择">
                        <el-option
                                v-for="item in state_list"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input type="text" v-model="formInline.name" placeholder="请输入方案名称" style="width: 200px;margin:0 10px"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="listArray">搜索</el-button>
                </el-form-item>
                <el-button class="pull-right" type="primary" size="small" @click="addTypeClick()">添加方案</el-button>
            </el-form>

            <el-table highlight-current-row :data="list" border size="mini" v-loading.body="listLoading">
                <el-table-column align="center" label='序号' width="50">
                    <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
                </el-table-column>
                <el-table-column align="center" label="标记色" prop="name" width="120px">
                    <template slot-scope="scope">
                        <div style="width: 100px;height: 25px;" :style="{background:scope.row.color}"></div>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="方案名称" prop="name"></el-table-column>
                <el-table-column align="center" label="创建时间" prop="create_time"></el-table-column>
                <el-table-column align="center" label="状态" width="100px">
                    <template slot-scope="scope">{{scope.row.status==1?"已启用":"已停用"}}</template>
                </el-table-column>
                <el-table-column align="center" label='操作' width="330">
                    <template slot-scope="scope">
                        <el-button  type="primary" plain size="mini" @click="signEnables(scope.row)">{{scope.row.status==1?'停用':'启用'}}</el-button>
                        <el-button  type="primary" plain size="mini" @click="stores(scope.row)">查看门店</el-button>
                        <el-button  type="primary" plain size="mini" @click="details(scope.row)">详情</el-button>
                        <el-button  type="primary" plain size="mini" @click="details(scope.row,1)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 弹框 -->
        <el-dialog  title="添加方案" :visible.sync="addTypeDialog" width="900px" :before-close="closeDialoig">
            <div class="op_title" style="margin-top: 0">基础信息</div>
            <el-form
                    :model="infoForm"
                    ref="infoForm"
                    :disabled="alter"
            >
                <el-form-item label="方案名称">
                    <el-input style="width: 280px" v-model="infoForm.name" placeholder="请输入方案名称"  maxlength="15" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="标记色">
                    <div class="main">
                        <div v-for="(item,index) in colorlist" :key="index" :style="{background:item.name}"
                             @click="addSelectColor(item.name)">
                            <span class="el-icon-check" v-show="item.name==infoForm.color"></span>
                        </div>
                    </div>
                </el-form-item>
                <div class="op_title" >积分规则</div>
                <el-table highlight-current-row :data="dialoigTableList" border size="mini" max-height="300px">
                    <el-table-column align="center" label='序号' width="50">
                        <template slot-scope="scope">{{scope.$index+1+(dialoigCurrentPage-1)*dialoigPageSize}}</template>
                    </el-table-column>
                    <el-table-column align="center" label="卡类型">
                        <template slot-scope="scope">
                            <div v-if="!scope.row.name && scope.$index+1 == dialoigTableList.length">
                                <el-select v-model="card_type_id" style="width:240px" @change="cardTypeChange">
                                    <el-option-group v-for="group in card_type_list" :key="group.type" :label="group.type_name">
                                        <el-option v-for="item in group.list" :key="item.id" :label="item.name" :value="item.id">
                                        </el-option>
                                    </el-option-group>
                                </el-select>
                            </div>
                            <div v-else>
                                <span>{{scope.row.type_name}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="规则">
                        <template slot-scope="scope">
                            <div v-if="!scope.row.rule && scope.$index+1 == dialoigTableList.length">
                                <span>消费</span>
                                <el-input style="width: 100px;margin: 0 5px" v-model="limit" placeholder="0~999999"></el-input>
                                <span>{{cardUnit}}得</span>
                                <el-input style="width: 100px;margin: 0 5px" v-model="score" placeholder="0~999999"></el-input>
                                <span>积分</span>
                            </div>
                            <div v-else>
                                <span>{{scope.row.rule}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label='操作' width="100">
                        <template slot-scope="scope">
                            <div v-if="!scope.row.rule&& scope.$index+1 == dialoigTableList.length">
                                <el-button type="primary" size="mini" :disabled="isDisabled" @click="addRelevance()">添加</el-button>
                            </div>
                            <div v-else>
                                <el-button :disabled="isDisabled" type="danger" size="mini" @click="delRelevance(scope.row)">移除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="margin: 20px 0;height: 40px">
                    <el-pagination class="pull-left" background @current-change="dialoigCurrentChange" :current-page.sync="dialoigCurrentPage" :page-size="dialoigPageSize"
                                   layout="prev, pager, next, jumper" :total="dialoigDataNumber">
                    </el-pagination>
                </div>

                <div class="main_botton" >
                    <span></span>
                    <div v-show="!alter">
<!--                        <el-button  type="primary" plain @click="closeDialoig(1)">关闭</el-button>-->
                        <el-button  type="primary" v-if="!isDisabled && !alter"  @click="saveClick()">保存</el-button>
                        <el-button  type="primary" v-else  @click="saveUpdate()">修改</el-button>
                    </div>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog  title="查看门店" :visible.sync="storeDialog" width="500px">
            <div class="stroe_dialog">
                <span>方案名称：{{storeDialogObj.name}}</span>
                <span :style="{background:storeDialogObj.color}"></span>
            </div>
            <el-table highlight-current-row :data="storeDialogList" border size="mini" max-height="300px">
                <el-table-column align="center" label='序号' width="50">
                    <template slot-scope="scope">{{scope.$index+1}}</template>
                </el-table-column>
                <el-table-column align="center" label='门店名称' prop="name"></el-table-column>
            </el-table>
        </el-dialog>
        <!-- 自定义底部 -->
        <div class="bottom_box">
            <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
                           layout="prev, pager, next, jumper" :total="totalDataNumber">
            </el-pagination>
        </div>
    </div>
</template>
<script>
    import {
        getStore,
        getCardList,
        signSave,
        getInfoPage,
        getInfo,
        signEnable,
        signDetails,
        rulesStore,
        rulesUpdate
    } from "@/api/operation/integral_scheme";

    import {
        pickerOptionsF,
        pickerDateOneMonth,
    } from "@/utils";

    import {
        notCharmap,
        num1to999999
    } from "@/utils/validate";
   let cardList=[];
    export default {
        name: 'integral_scheme',
        data(){
            return{
                list: null,  //数据
                store_list:[],
                card_old_list:[],
                card_type_list:[],
                storeDialogList:[],
                storeDialogObj:"",
                pickerOptions: pickerOptionsF(),
                pickerDate: pickerDateOneMonth(),
                top_title:"签到方案配置",
                listLoading: false,  //表格换场动画
                isDisabled:false, //是否可更改
                alter:false,
                currentPage: 1,
                totalDataNumber: 0,
                state_list:[{id:"-1",name:"全部"},{id:"0",name:"已停用"},{id:"1",name:"已启用"}],
                colorlist:[{id:"0",name:"#eb2fa3"},{id:"1",name:"#8756df"},{id:"2",name:"#1890ff"},{id:"3",name:"#13c5d0"}
                    ,{id:"4",name:"#f5222d"},{id:"5",name:"#fa8c16"},{id:"6",name:"#52c41a"}],
                addTypeDialog: false, // 弹窗是否显示
                storeDialog:false, // 弹窗是否显示
                formInline: {  //开始时间，结束时间
                    begin_time: "",
                    end_time: "",
                    store_id:"",
                    status:"1",
                    name:""
                },
                //表格添加数据
                card_type_id:"",
                cardUnit:"",
                score:"",
                limit:"",
                dialoigTableList:[{}],
                dialoigPageSize:5,
                dialoigCurrentPage:1,
                dialoigDataNumber:0,
                infoForm:{  //弹框数据
                    name:"",
                    color:"",
                    ruleId:"",
                    json_list:[],
                }
            }
        },
        mounted() {
            this.getstore();
            this.getCardType();
        },
        methods:{
            getstore() {
                getStore({ category_id: 717 }).then((response) => {
                    this.store_list = response;
                    this.formInline.store_id = response[0].id;
                    this.timeListArray();
                }).then(()=>{
                    this.listArray();
                })
            },
            timeListArray(){  //时间选择
                this.formInline.begin_time=this.pickerDate[0];
                this.formInline.end_time=this.pickerDate[1];
            },
            listArray(){  //获取数据
                this.listLoading = true;
                this.list = [];
                getInfoPage(this.formInline).then(response=>{
                    this.totalDataNumber = response.data.count / 1;
                    if (this.totalDataNumber == 0) {
                        this.listLoading = false;
                    } else {
                        getInfo(this.formInline).then(res=>{
                            this.list = res.data;
                            this.listLoading = false;
                        });
                    }
                });
            },
            handleCurrentChange(val) {  //获取某个分页的数据
                this.listLoading = true;
                getInfo(this.formInline,val).then(res=>{
                    this.list = res.data;
                    this.listLoading = false;
                }).catch(res => {
                    this.listLoading = false;
                });
            },
            saveUpdate(){  //修改
                if(!notCharmap(this.infoForm.name)){
                    this.$message.error("请填写正确的方案名称");
                    return
                }
                if(!this.infoForm.color){
                    this.$message.error("请选择方案标记色");
                    return
                }
                rulesUpdate({
                    id:this.infoForm.ruleId,
                    store_id:this.formInline.store_id,
                    name:this.infoForm.name,
                    color:this.infoForm.color,
                }).then((res)=>{
                    if(res.code==1){
                        this.listArray();
                        this.clearDate();
                        this.addTypeDialog = false;
                        this.$message.success(res.message);
                    }
                })
            },
            saveClick(){
                let json_list=[];
                if(!notCharmap(this.infoForm.name)){
                    this.$message.error("请填写正确的方案名称");
                    return
                }
                if(!this.infoForm.color){
                    this.$message.error("请选择方案标记色");
                    return
                }

                if(this.infoForm.json_list.length == 0){
                    this.$message.error("请添加积分规则");
                    return
                }
                // console.log(this.infoForm);
                let json=[];
                for(let i=0;i<this.infoForm.json_list.length;i++){
                    json.push({
                        card_type_id:this.infoForm.json_list[i].card_type_id,
                        limit:this.infoForm.json_list[i].limit,
                        score:this.infoForm.json_list[i].score,
                    })
                }
                let data={
                    store_id:this.formInline.store_id,
                    name:this.infoForm.name,
                    color:this.infoForm.color,
                    json_list:json,
                }
                // console.log(data)

                signSave(data).then(res=>{
                    if(res.code==1){
                        this.$confirm('保存成功，是否去配置方案', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(()=>{
                            this.listArray();
                            this.clearDate();
                            this.addTypeDialog = false;
                            this.$message.success(res.message);
                            this.$router.push({
                                name:"operation/integral_rule"
                            });
                        }).catch(() => {
                            this.listArray();
                            this.clearDate();
                            this.addTypeDialog = false;
                            this.$message.success(res.message);
                        });
                    }
                })
            },
            signEnables(row){
                if(row.status==1){
                    this.$confirm('是否确定停用该方案？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(()=>{
                        signEnable({id:row.id,status:"0",store_id:this.formInline.store_id}).then(res=>{
                            if(res.code==1){
                                this.$message.success(res.message);
                                this.listArray();
                            }
                        });
                    }).catch(() => {
                        row.status = true;
                    });
                }else{
                    signEnable({id:row.id,status:"1",store_id:this.formInline.store_id}).then(res=>{
                        if(res.code==1){
                            this.$message.success(res.message);
                            this.listArray();
                        }
                    });
                }
            },
            details(row,index){
                signDetails({id:row.id}).then(res=>{
                    if(res.code==1 && res.data.length!=0){
                        this.addTypeDialog = true;
                        this.isDisabled=true;
                        if(index){
                            this.alter = false;
                        }else{
                            this.alter = true;
                        }
                        console.log(this.colorlist.filter(item=>item.name == res.data[0].color));
                        this.infoForm.name = row.name;
                        this.infoForm.ruleId = row.id;

                        this.infoForm.color = this.colorlist.filter(item=>item.name == res.data[0].color)[0].name;

                        this.infoForm.json_list = res.data; //全部数据
                        this.dialoigDataNumber = this.infoForm.json_list.length / 1;  //数据数量

                        let arraylist;
                        let num = this.dialoigCurrentPage * this.dialoigPageSize;

                        if(this.dialoigDataNumber<=this.dialoigPageSize){
                            arraylist = this.infoForm.json_list.slice(0,this.dialoigPageSize);
                        }else{
                            arraylist = this.infoForm.json_list.slice(num-this.dialoigPageSize,num);
                        }
                        this.dialoigTableList = arraylist;

                        this.dialoigTableList.forEach(value => {
                            value.rule =`消费${value.limit}${value.type==0?'币':value.type=='1'?'次':'星'}得${value.score}积分`
                        })

                    }else{
                        this.addTypeDialog = true;
                        this.isDisabled=true;
                        this.dialoigTableList = [];
                    }
                });
            },
            dialoigCurrentChange(val){
                let num = val * this.dialoigPageSize;
                let array = this.infoForm.json_list.slice(num-this.dialoigPageSize,num);
                this.dialoigTableList=[...array,[{}]];
            },
            addRelevance(){ //添加商品
                if(!this.card_type_id){
                    this.$message.error("请先选择卡类型");
                    return
                }
                if(!num1to999999(this.limit)){
                    this.$message.error(`请填写消费${this.cardUnit}数`);
                    return
                }
                if(!num1to999999(this.score)){
                    this.$message.error("请填写获得积分数");
                    return
                }

                let cardName = this.card_old_list.filter(item => item.id == this.card_type_id)[0];
                let array=[{
                    type_name:cardName.name,
                    card_type_id:this.card_type_id,
                    limit:this.limit,
                    score:this.score,
                    rule:`消费${this.limit}${this.cardUnit}得${this.score}积分`
                }]

                this.infoForm.json_list=[...array,...this.infoForm.json_list];  //全部数据
                console.log(this.infoForm.json_list)
                this.dialoigDataNumber = this.infoForm.json_list.length / 1;  //数据数量

               this.card_old_list.splice(this.card_old_list.findIndex(itam => itam === cardName), 1);
               this.card_type_list = this.cardTypeGroup(this.card_old_list);

                let arraylist;
                let num = this.dialoigCurrentPage * this.dialoigPageSize;

                if(this.dialoigDataNumber<=this.dialoigPageSize){
                    arraylist = this.infoForm.json_list.slice(0,this.dialoigPageSize);
                }else{
                    arraylist = this.infoForm.json_list.slice(num-this.dialoigPageSize,num);
                }
                this.dialoigTableList=[...arraylist,[{}]];

                this.cardUnit="";
                this.limit="";
                this.score="";
                this.card_type_id="";
            },
            delRelevance(array){ //移除商品
                this.card_old_list.push(cardList.filter(item => item.id == array.card_type_id)[0]);
                this.card_type_list = this.cardTypeGroup(this.card_old_list);
                this.infoForm.json_list.splice(this.infoForm.json_list.findIndex(itam => itam === array), 1);

                let num = this.dialoigCurrentPage * this.dialoigPageSize;
                this.dialoigDataNumber = this.infoForm.json_list.length / 1;  //数据数量
                let arraylist;
                if(this.dialoigDataNumber<=this.dialoigPageSize){
                    arraylist = this.infoForm.json_list.slice(0,this.dialoigPageSize);
                }else{
                   let list = this.infoForm.json_list.slice(num-this.dialoigPageSize,num);
                   if(list.length==0){
                       let number = (this.dialoigCurrentPage-1) * this.dialoigPageSize;
                       arraylist = this.infoForm.json_list.slice(number-this.dialoigPageSize,number);
                   }else{
                       arraylist = this.infoForm.json_list.slice(num-this.dialoigPageSize,num);
                   }
                }
                this.dialoigTableList=[...arraylist,[{}]];

            },
            addSelectColor(name){
                if(!this.alter){
                    this.infoForm.color = name;
                }
            },
            //获取卡类型
            getCardType() {
                getCardList({}).then(res => {
                    if (res.code == 1) {
                        cardList = JSON.parse(JSON.stringify(res.data));
                        this.card_old_list = res.data;
                        this.card_type_list = this.cardTypeGroup(res.data);
                    }
                });
            },
            cardTypeChange(val) {
                let obj = this.card_old_list.filter(item => item.id == val)[0];
                console.log(obj);
                if(obj.type==0){
                    this.cardUnit = "币";
                }else if(obj.type==1){
                    this.cardUnit = "次";
                }else {
                    this.cardUnit = "星";
                }
            },
            // 卡类型分组
            cardTypeGroup(data) {
                let map = {};
                data.forEach(i => {
                    if (!map[i.type]) {
                        map[i.type] = {
                            type: i.type,
                            type_name:
                                i.type == 0
                                    ? "币"
                                    : i.type == 1
                                    ? "次"
                                    : i.type == 2
                                        ? "星星"
                                        : "",
                            list: [{ id: i.id, name: i.name, disabled: false }]
                        };
                    } else {
                        map[i.type].list.push({
                            id: i.id,
                            name: i.name,
                            disabled: false
                        });
                    }
                });
                let list = [];
                for (var i in map) {
                    list.push(map[i]);
                }
                return list;
            },
            addTypeClick() {
                this.alter = false;
                this.isDisabled = false;
                this.addTypeDialog = true;
            },
            stores(row){  //查看门店
               this.storeDialogList=[];
               this.storeDialogObj=row;
                rulesStore({
                    id:row.id
                }).then((res)=>{
                    if(res.code==1){
                        this.storeDialogList=res.data;
                        this.storeDialog = true;
                    }
                })
            },
            clearDate(){
                this.cardUnit="";
                this.limit="";
                this.score="";
                this.card_type_id="";
                this.dialoigTableList=[{}];
                this.infoForm={
                    ruleId: "",
                    name:"",
                    color:"",
                    json_list:[]
                }
                this.dialoigDataNumber = 0;
                this.card_old_list = JSON.parse(JSON.stringify(cardList));
                this.card_type_list = this.cardTypeGroup(this.card_old_list);
            },
            closeDialoig(){
                if(!this.isDisabled || !this.alter){
                    this.$confirm("方案尚未保存，关闭后数据清空，是否关闭", "提示", {
                        type: "warning"
                    }).then(() => {
                        this.clearDate();
                        this.addTypeDialog = false;
                    }).catch(()=>{
                        this.addTypeDialog = true;
                    });
                }else{
                    this.clearDate();
                    this.addTypeDialog = false;
                }
            }
        }
    };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .customContainer {
        overflow-y: auto;
    }
    .main{
        display: flex;
        flex-wrap: wrap;
        div{
            width: 40px;
            height: 40px;
            margin-right:10px;
            position: relative;

            span{
                color: white;
                font-size: 28px;
                font-weight: bold;
                position: absolute;
                bottom: 5px;
                right: 5px;
            }
        }
    }
    .op_title {
        margin: 30px 0 20px;
        font-size: 18px;
        font-weight: bold;
        color: #282828;
        padding:0 0 10px 0px;
        box-sizing: border-box;
        border-bottom: 1px solid #dcdfe6;
    }

    .main_botton{
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        button{
            width: 100px;
            height: 35px;
            line-height: 10px;
        }
    }
    .stroe_dialog{
        margin-bottom: 15px;
        display: flex;
        align-items: center;

        span:nth-child(2){
            display: block;
            width: 80px;
            height: 35px;
            margin-left: 20px;
        }
    }
</style>
